<template>
  <div class="permission">
    <div class="title">{{ lang.t('page.user.account.permission') }}</div>
    <el-row :gutter="20">
      <el-col :span="12" v-for="item in permissionModel.getList()" :key="item.id">
        <div 
          class="item flash" 
          :class="{'on': permission ? permission.includes(item.id) : false }" 
          @click="onSelect('permission', item.id)"
        >
          <div class="name">
            {{ item.name }}
          </div>
          <div class="body wrap">
            {{ lang.t('permission.' + item.id + '.content') }}
          </div>
        </div>
      </el-col>
    </el-row>
    <div class="title">{{ lang.t('page.user.account.plugin') }}</div>
    <el-row :gutter="20">
      <el-col :span="8" v-for="item in pluginData" :key="item.id()">
        <div 
          class="item flash" 
          :class="{'on': plugin ? plugin.includes(item.id()) : false }" 
          @click="onSelect('plugin', item.id())"
        >
          <img :src="item.img()" />
          <div class="name wrap">
            {{ item.name() }}
          </div>
          <div class="body wrap">
            {{ item.content() }}
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { ref } from 'vue'
import app from '@/app'
import userModel from '@/model/user'
import permissionModel from '@/model/permission'
import pluginModel from '@/model/plugin'

export default {
  props: ['permission', 'plugin'],
  setup(props, { emit }) {
    const onSelect = (type, id) => {
      // 数组深拷贝
      const data = [...props[type]]
      
      if(data.includes(id)) {
        data.splice(data.findIndex(find => find == id), 1)
      } else {
        data.push(id)
      }

      emit('update:' + type, data)
    }

    // 加载插件
    const pluginData = ref({})
    pluginModel.getId(userModel.getData().plugin).then(res => {
      pluginData.value = res
    })

    // 加载权限
    permissionModel.get(userModel.getData().permission)

    return {
      lang: app.lang,
      pluginData,
      permissionModel,
      onSelect
    }
  }
} 

</script>